// api.js

class API {
	
	constructor(baseUrl = '', timeout = 60000) {
		this.baseUrl = baseUrl;
		// this.token = ""; // 正式包注释掉 
		this.timeout = timeout; // 设置默认超时时间为60秒
	}

	// setToken(token) {
	// 	this.token = token;
	// }
	
	

	get(url, params = {}, contentType = 'application/json') {
		return this.request(url, params, 'GET', contentType);
	}

	post(url, params = {}, contentType = 'application/json') {
		return this.request(url, params, 'POST', contentType);
	}
	upload(url, params = {}, contentType = 'multipart/form-data') {
		return this.uploads(url, params, contentType);
	}

	// 文件上传
	uploads(url, data, contentType = 'multipart/form-data'){
		this.token = uni.getStorageSync("token") ? uni.getStorageSync("token") :
			""; // 默认为空字符串
		return new Promise((resolve, reject) => {
			const header = {
				'Content-Type': contentType // 添加Content-Type头部
			};
			
			if (this.token) {
				header['token'] = this.token; // 在请求头中添加token
			}
			uni.uploadFile({
				url: this.baseUrl + url, // 示例接口地址，根据实际情况调整
				filePath: data,
				name: 'file',
				header: header,
				success: (res) => {
					res = JSON.parse(res.data)
					if(res.code == 0){
						uni.showToast({
							icon:"none",
							title:res.msg
						})
					}
					resolve(res);
				},
				fail: (error) => {
					reject(error);
				},
			});
		});
	}

	// 普通请求
	request(url, params = {}, method = 'GET', contentType = 'application/json') {
		this.token = uni.getStorageSync("token") ? uni.getStorageSync("token") :
			""; // 默认为空字符串
		const header = {
			'Content-Type': contentType // 添加Content-Type头部
		};
		 
		if (this.token) {
			header['token'] = this.token; // 在请求头中添加token
		}
		return new Promise((resolve, reject) => {
				uni.request({
					url: this.baseUrl + url,
					data: params,
					method: method,
					header: header,
					timeout: this.timeout, // 设置超时时间
					success: (res) => {
						
						if(res.data.code == 0){
							resolve(res.data);
						}else if(res.data.code == 1006){
							resolve(res.data);
						}else {
							if(res.data.code == 401){
								uni.redirectTo({
									url:"/pages/index/login"
								})
								return
							}
							uni.showToast({
								icon:"none",
								title:res.data.msg
							})
						}
					},
					fail: (err) => {
						// 请求失败，返回错误信息
					
						reject("失败",err);
					}
				});
			})
			.catch((err) => {
				// 捕获并处理异常
				console.error('请求失败：', err);
				throw err; // 抛出错误
			});
	}
}

export default API;